package com.dkm.biz.gl.util;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.math.RandomUtils;


/**
 * 随机号码生成工具类
 * @author 严华军
 *
 */
public class CodeUtil {

	private static final byte CHAR_A = (byte)'A';
	private static final byte CHAR_Z = (byte)'Z';
	private static final byte CHAR_0 = (byte)'0';
	private static final byte CHAR_9 = (byte)'9';
	
	private static final byte[] ALPHA;
	private static final byte[] DIGITAL;
	private static final byte[] CHARS;
	private static final int ALPHA_LEN;
	private static final int DIGITAL_LEN;
	private static final int CHARS_LEN;
	
	static{
		ALPHA_LEN = CHAR_Z - CHAR_A + 1;
		DIGITAL_LEN = CHAR_9 - CHAR_0 + 1;
		CHARS_LEN = (byte)(ALPHA_LEN + DIGITAL_LEN);
		
		ALPHA = new byte[ALPHA_LEN];
		for(int i = 0; i < ALPHA_LEN; i++){
			ALPHA[i] = (byte)(CHAR_A + i);
		}
		
		DIGITAL = new byte[DIGITAL_LEN];
		for(int i = 0; i < DIGITAL_LEN; i++){
			DIGITAL[i] = (byte)(CHAR_0 + i);
		}
		
		CHARS = ArrayUtils.addAll(DIGITAL, ALPHA);
	}
	
	/**
	 * 生成CODE
	 * @param prefix 前缀
	 * @param len 除前缀外的长度
	 * @param onlyDigital 是否只生成数字，否则数字字母混合
	 * @return
	 * @throws Exception
	 */
	public static String generate(String prefix, int len, boolean onlyDigital){
		ByteBuffer buf = ByteBuffer.allocate(len);
		byte r = 0;
		byte[] tmp;
		int tmpLen;
		
		if(onlyDigital){
			tmp = DIGITAL;
			tmpLen = DIGITAL_LEN;
		}else{
			tmp = CHARS;
			tmpLen = CHARS_LEN;
		}
		
		for(int i = 0; i < len; i++){
			r =  tmp[ RandomUtils.nextInt(tmpLen) ];
			buf.put(r);
		}
		
		String code = "";
		try {
			code = new String( buf.array(), "UTF-8" );
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		buf.clear();
		
		return prefix != null ? prefix.concat(code) : code;
	}
	
}
